package com.kaishengit.web;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.kaishengit.dao.ProjectDao;
import com.kaishengit.dao.Project_UserDao;
import com.kaishengit.dao.UserDao;
import com.kaishengit.entity.Project;
import com.kaishengit.entity.Project_User;
import com.kaishengit.entity.User;

public class New_Project extends HttpServlet {

	
	
	private static final long serialVersionUID = 1L;


	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		UserDao udao = new UserDao();
		List<User> ulist = new ArrayList<User>();
		ulist = udao.findAll();
		request.setAttribute("userlist", ulist);
		request.getRequestDispatcher("WEB-INF/views/new_project.jsp").forward(request, response);
		
	}


	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		String[] nameArray;
		String projectname = request.getParameter("projectname");
		String description = request.getParameter("description");
		String manager = request.getParameter("manager");
		String project_member = request.getParameter("project_member");
		nameArray = project_member.split(",");
		ProjectDao pdao = new ProjectDao(); 
		UserDao udao = new UserDao();
		Project_UserDao pudao = new Project_UserDao();
		Project p = new Project();
		p.setManager(manager);
		p.setProjectDescription(description);
		p.setProjectName(projectname);
		p.setProjectNumbers(project_member);
		pdao.insertNewProject(p);
		int  projectID = pdao.findByProjectName(projectname).getId(); 
		nameArray = project_member.split(",");
		for(int i=0;i<nameArray.length;i++){
			String membername = null;
			membername = nameArray[i];
			User member = udao.findByUsername(membername);
			if(member!=null){
				Project_User pu = new Project_User();
				pu.setProjectID(projectID);
				pu.setUserID(member.getId());
				pudao.insertPUByPU(pu);
			}
			
		}
		response.sendRedirect("main.jspx");
	}

}
